import { useModel } from "umi";
import { useReactive } from "ahooks";
import { useEffect } from "react";
import { Table, message } from "antd";

import { AllIndustryTypes } from "../../_graphql/public";
import { CreateIndustryType } from "../../_graphql/organizations";

const SettingIndustryType = ({ industryTypes, reloadData }) => {
    const { graphqlFetchPlatform } = useModel("global");
    const { currentOrganizationUuid } = useModel("organization.info");
    const { onCloseGlobalModal } = useModel("global.modal");

    const state = useReactive({
        loading: false,
        data: [],
    });

    const loadDate = async () => {
        state.loading = true;
        let res = await graphqlFetchPlatform({ query: AllIndustryTypes, variables: {} });
        state.data = res?.a?.nodes?.filter((item) => industryTypes.findIndex((_item) => _item.itUuid === item.itUuid) === -1) || [];
        state.loading = false;
    };

    useEffect(() => {
        loadDate();
    }, []);

    const updateIndustryType = async (industryType) => {
        let query = `query MyQuery($itDbna: String!, $oiUuid: UUID!) { a: allOrganizationIndustryTypes(condition: {itDbna: $itDbna, oiUuid: $oiUuid}) { totalCount } }`;
        let res = await graphqlFetchPlatform({ query, variables: { oiUuid: currentOrganizationUuid, itDbna: industryType.itDbna } });
        if (res?.a?.totalCount > 0) return message.warning(`数据服务名称[${industryType.itDbna}]已存在, 不能添加新的行业信息`);
        if (res && res?.a?.totalCount === 0) {
            res = await graphqlFetchPlatform({
                query: CreateIndustryType,
                variables: {
                    oiUuid: currentOrganizationUuid,
                    itUuid: industryType.itUuid,
                    itRedb: industryType.itRedb,
                    itDbna: industryType.itDbna,
                    itHbpa: industryType.itHbpa,
                    itType: industryType.itType,
                },
            });
            if (res) {
                reloadData();
                onCloseGlobalModal();
            }
        }
    };

    return (
        <Table loading={state.loading} dataSource={state.data} size="small" bordered pagination={false} rowKey="itUuid">
            <Table.Column title="行业名称" dataIndex="itName" align="left" />
            <Table.Column title="操作" align="center" render={(_, r) => <a onClick={() => updateIndustryType(r)}>选择</a>} />
        </Table>
    );
};

export default SettingIndustryType;
